import { useEffect, useState } from "react";
import Chat, { Bubble, useMessages } from "@chatui/core";
import { db, auth } from "./cloud";
import "./assets/App.css";
import "@chatui/core/es/styles/index.less";
import "@chatui/core/dist/index.css";
import "./assets/chatui-theme.css";
import Loading from "./assets/loading.svg";

// 保存获取到的随机图片
let pic = "";
// 记录监听次数
let count = 0;
function App() {
  const [loading, setLoading] = useState(true);
  // chatUi 自定义的hooks
  const { messages, appendMsg } = useMessages([
    {
      type: "text",
      content: { text: "欢迎进入聊天室~" },
      user: {
        avatar:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201802%2F05%2F20180205002036_qebfm.thumb.700_0.jpg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621592722&t=da04cf36169eb3f752e8721e698f168d",
      },
      hasTime: true,
    },
  ]);

  // 获取随机图片的方法
  function getPic() {
    var ajax = new XMLHttpRequest();
    ajax.open("get", "https://api.uomg.com/api/rand.avatar");
    ajax.send();
    ajax.onreadystatechange = function (res) {
      // 因地址重定向，拿到的地址即为图片地址
      pic = res.target.responseURL;
    };
  }

  useEffect(() => {
    async function init() {
      getPic();
      if (!auth.hasLoginState()) {
        // 判断是否登录，进行登录
        await auth.anonymousAuthProvider().signIn();
      }
      // 选择数据库，进行监听
      await db.collection("message").watch({
        onChange(snapshot) {
          // 取消息，拿到最新一条添加
          const arr = snapshot.docs;
          const mess = arr[arr.length - 1];
          uiAppendMsg(mess);
          setLoading(false);
        },
        onError() {},
      });
    }
    init();
  }, []);

  async function handleSend(type, val) {
    // 发送消息
    if (type === "text" && val.trim()) {
      const message = {
        timestamp: Date.now(),
        text: val,
        pic: pic
          ? pic
          : "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-6afa72220d29f045c15217aa6b275808_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621595413&t=c23ab3b48d9198ab047b101f8dabd1da",
      };
      await db.collection("message").add(message);
    }
  }

  function uiAppendMsg(mess) {
    if (count === 0) {
      // 不能看到进房间之前的消息
      count++;
      return;
    }
    let uid = auth.hasLoginState().user.uid;
    appendMsg({
      type: "text",
      content: { text: mess.text },
      position: mess._openid === uid ? "right" : "left",
      user: {
        avatar: mess.pic,
      },
      hasTime: true,
    });
  }

  function renderMessageContent(msg) {
    const { content } = msg;
    return <Bubble content={content.text} />;
  }

  return (
    <div className="App">
      {loading ? (
        <div className="load">
          <img src={Loading} className="App-loading" alt="logo" />
          <div>登录中...</div>
        </div>
      ) : (
        <Chat
          navbar={{ title: "匿名聊天室" }}
          messages={messages}
          renderMessageContent={renderMessageContent}
          onSend={handleSend}
        />
      )}
    </div>
  );
}

export default App;
